package com.fl.nacostest.consumer;

import com.alibaba.fastjson.JSON;
import com.fl.nacostest.Log;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: fulin
 * @Date: 2022/08/04/17:34
 * @Description:
 */
@Component
public class KafkaConsumer {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @KafkaListener(topics = {"my-replicated-topic4"})
    public void onMessage(ConsumerRecord<?, String> record) throws Exception {
        IndexRequest indexRequest = new IndexRequest("logs");
        Log log = JSON.parseObject(record.value(), Log.class);
        if (log.getTime() == null && log.getInfo() == null) return;
        Map<String, String> map = new HashMap<>();
        map.put("time", log.getTime());
        map.put("info", log.getInfo());
        indexRequest.source(map).id(UUID.randomUUID().toString().replace("-",""));
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }
}
